﻿#include "as_address.h"

#ifdef _WIN32
#else
#endif
as::net::Address::Address(uint16 port /*= 0*/, bool isLocal /*= false*/, bool isIpv6 /*= false*/)
{
	if (isIpv6)
	{
		memset(&addr6_, 0, sizeof(addr6_));
		addr6_.sin6_family = AF_INET6;
		addr6_.sin6_addr = isLocal ? in6addr_loopback : in6addr_any;
		addr6_.sin6_port = htons(port);
	}
	else
	{
		memset(&addr_, 0, sizeof(addr_));
		addr_.sin_family = AF_INET;
		addr_.sin_addr.s_addr = isLocal ? INADDR_LOOPBACK : INADDR_ANY;
		addr_.sin_port = htons(port);
	}
}

as::net::Address::~Address()
{

}

sockaddr* as::net::Address::GetSockAddr() const
{
	return static_cast<sockaddr*>((void*)&addr6_);
}

int as::net::Address::GetAF() const
{
	return addr_.sin_family;
}

uint16 as::net::Address::GetPort() const
{
	return ntohs(addr_.sin_port);
}

int as::net::Address::GetLen() const
{
	return sizeof(addr6_);
}

std::string as::net::Address::GetAddr() const
{
	std::string str;
	str.resize(INET_ADDRSTRLEN);
	inet_ntop(AF_INET, &(addr_.sin_addr), &str[0], INET_ADDRSTRLEN);
	return str;
}

as::net::Address::Address(std::string_view addr, uint16 port, bool isIpv6 /*= false*/)
{
	if (isIpv6)
	{
		memset(&addr6_, 0, sizeof(addr6_));
		addr6_.sin6_family = AF_INET6;
		inet_pton(addr6_.sin6_family, addr.data(), &addr6_.sin6_addr);
		addr6_.sin6_port = htons(port);
	}
	else
	{
		memset(&addr_, 0, sizeof(addr_));
		addr_.sin_family = AF_INET;
		inet_pton(addr_.sin_family, addr.data(), &addr_.sin_addr);
		addr_.sin_port = htons(port);
	}
}


